package npu.dce.andcontact1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Handler;

class Server_Invite implements Runnable{
    
	private String SERVERIP = "10.0.2.15";		
    private int SERVERPORT_INVITE = 500;
	
    private String CLIENTIP = "10.0.2.2";  
    private int CLIENTPORT_ACCEPT = 600;
    
    private UpdatePacket update;
    private boolean update_contact;
    
    private String strJoin; 
    
    private String Version, Owner, Types, GivenName, MiddleName, FamilyName, Gender, SpinPhone, Phone, SpinEmail, 
    	   Email, SpinIM, IM, SpinPostalAddr, Street, POBox, City, State, ZipCode, Country, SpinSNS, SNS, 
    	   SpinOrg1, Org1, SpinOrg2, Org2, Notes, Time;

    private byte[] photo, buf, receive_data;
    private long packetTime, dbTime, contact_id;
    private int count = 0;
    
	private ContactDBAdapter mDbHelper_server;
	private DatagramSocket socket;
	private UpdatePacket total_contact;

	private InetAddress inetadd;
	private Context context;
	private Handler handler;
	private DatagramPacket send_packet, receive_packet;
	private InetAddress iadd;
	private String value, stringUpdate;

	private Cursor cur;
	
    public Server_Invite(Context context,Handler handler, UpdatePacket total, ContactDBAdapter mDbHelper) {
            this.context = context;
            this.handler = handler;
            total_contact = total;
            mDbHelper_server = mDbHelper;
    }
 
    @Override
    public void run() {
    	
    	// TODO Auto-generated method stub        
        	try {
        		            		
        		inetadd = InetAddress.getByName(SERVERIP);        		
        		socket = new DatagramSocket(SERVERPORT_INVITE, inetadd);        		

        		while(true){                	

        			try{
        				
        				buf = new byte[1920];
        				receive_packet= new DatagramPacket(buf,buf.length);
        				                       
        				socket.receive(receive_packet);
        				
        				receive_data = receive_packet.getData();
        				value = new String(receive_data);
        				    				
        				strJoin = new JSONObject(value).getString("Join");
        				           					
        			    handler.post(new Runnable(){

        			    	public void run(){
        			            		
        			    		AlertDialog.Builder builder = new AlertDialog.Builder(context);

        			            builder.setTitle("Group Join");                    
        			           	builder.setIcon(R.drawable.icon);
        			           	builder.setMessage("Do you want to join? " + strJoin);
        			           	builder.setPositiveButton("Yes", null);
        			           	builder.setNegativeButton("No", null);
        			           	 	  	 
        			           	cur = mDbHelper_server.fetchAllContacts(); 
        			           	 	             			           	 	 
        			           	if(cur != null){
        			           		if (cur.moveToFirst()){
	            		        			            	            		        			
        			           			do{
	            		        				     
        			           				Version = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_VERSION));  
        			           	 	  		Types = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_TYPES));
        			           	 	  		Owner = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_OWNER));
        			           	 	  		GivenName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_GIVENNAME));
        			           	 	  		MiddleName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_MIDDLENAME));
        			           	 	  		FamilyName = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_FAMILYNAME));
		            		        		Gender = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_GENDER));
		            		        		SpinPhone = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINPHONE));
		            		        		Phone = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_PHONE));
		            		        		SpinEmail = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINEMAIL));
		            		        		Email = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_EMAIL));
		            		        		SpinIM = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINIM));
		            		        		IM = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_IM));
		            		        		SpinPostalAddr = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINADDR));
		            		        		Street = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_STREET));
		            		        		POBox = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_POBOX));
		            		        		City = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_CITY));
		            		        		State = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_STATE));
		            		        		ZipCode = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ZIPCODE));
		            		        		Country = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_COUNTRY));
		            		        		SpinSNS = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINSNS));
		            		        		SNS = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SNS));
		            		        		SpinOrg1 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINORG1));
		            		        		Org1 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ORG1));
		            		        		SpinOrg2 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_SPINORG2));
		            		        		Org2 = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_ORG2));            		            			
		            		        		Notes = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_NOTES));
		            		        		Time = cur.getString(cur.getColumnIndex(ContactDBAdapter.KEY_TIME));
		            		        		photo = cur.getBlob(cur.getColumnIndex(ContactDBAdapter.KEY_PHOTO));
		            		        				
		            		        		update = new UpdatePacket(photo.length);
		            		        					
        			           	 	  		if( Owner.compareTo("Y") ==  0 ){ 
		            		        					
        			           	 	  			update.setVersion(Version);
        			           	 	  			update.setTypes("join");
        			           	 	  			update.setGivenName(GivenName);   
        			           	 	  			update.setMiddleName(MiddleName);   
        			           	 	  			update.setFamilyName(FamilyName);           
        			           	 	  			update.setGender(Gender);                    
        			           	 	  			update.setSpinPhone(SpinPhone);                    
        			           	 	  			update.setPhone(Phone);                    
        			           	 	  			update.setSpinEmail(SpinEmail);                    
        			           	 	  			update.setEmail(Email);                     
        			           	 	  			update.setSpinIM(SpinIM);                    
        			           	 	  			update.setIM(IM);                     
        			           	 	  			update.setSpinPostalAddr(SpinPostalAddr);                    
        			           	 	  			update.setStreet(Street);                    
        			           	 	  			update.setPOBox(POBox);                    
        			           	 	  			update.setCity(City);                   
        			           	 	  			update.setState(State);                    
        			           	 	  			update.setZipCode(ZipCode);                    
        			           	 	  			update.setCountry(Country);                    
        			           	 	  			update.setSpinSNS(SpinSNS);                    
        			           	 	  			update.setSNS(SNS);                    
        			           	 	  			update.setSpinOrg1(strJoin);                   
        			           	 	  			update.setOrg1(Org1);
        			           	 	  			update.setSpinOrg2(SpinOrg2);                   
        			           	 	  			update.setOrg2(Org2);
        			           	 	  			update.setNotes(Notes);
        			           	 	  			update.setTime(Time);
        			           	 	  			update.setPhotoSize(Integer.toString(photo.length));												 
        			           	 	  			update.setPhoto(photo);
	                                               
        			           	 	  					         	                                         
        			           	 	  			try {
        			           	 	  				send_packet = new DatagramPacket(buf,buf.length);
        			           	 	  				iadd = InetAddress.getByName(CLIENTIP);      
        			           	 	  			} catch (UnknownHostException e) {
        			           	 	  				// TODO Auto-generated catch block
													e.printStackTrace();
												} catch (IOException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												} 
														
        			           	 	  			} 		            		        				
        			           	 	  		} while (cur.moveToNext());    //while
        			           	 	  	  }
        			           	 	    }	
        			           	 	 
        			           	 	  	 builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {						
        									@Override
        									public void onClick(DialogInterface dialog, int which) {
        										
        										send_packet=new DatagramPacket( update.update_packet, update.update_packet.length, iadd, CLIENTPORT_ACCEPT);    	            								
        										
        										try {            											            											 					
													socket.send(send_packet);													
												} catch (IOException e) {
													// TODO Auto-generated catch block
													e.printStackTrace();
												}    
        										
        									}            								            			           	 	  	 
        			           	 	  	 });
        			           	 	  	
        			           	 	  	 builder.setNegativeButton("No", new DialogInterface.OnClickListener() {						
        									@Override
        									public void onClick(DialogInterface dialog, int which) {
        										// TODO Auto-generated method stub            										
        										dialog.cancel();              										
        									}
        								 });  
        				 
        			           	 	  	 builder.show();  
        			           	 	     
        			            	 } // run    
        			            	
        			             }); // handler
            
        			} catch(IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    } catch(NullPointerException e) {
                    	e.printStackTrace();	
                    } catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}                                        
        		} //while          		         		
        } catch (UnknownHostException e) {
        	// TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NumberFormatException e){
		    e.printStackTrace();
		} catch (SocketException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();       
        }     
    } //run    
} //Server_Invite